package com.ruoyi.project.access.service;

import com.ruoyi.project.access.domain.*;
import com.ruoyi.project.decision.algorithms.CcfAlgorithm;
import com.ruoyi.project.decision.domain.CcfScores;
import com.ruoyi.project.decision.service.DataDecisionService;
import com.ruoyi.project.fusion.algorithms.*;
import com.ruoyi.project.fusion.domain.*;
import com.ruoyi.project.fusion.mapper.DataFusionMapper;
import com.ruoyi.project.fusion.service.DataFusionService;
import com.ruoyi.project.knowledge.algorithms.DataOptimizationAlgorithm;
import com.ruoyi.project.knowledge.domain.OverallAggScores;
import com.ruoyi.project.knowledge.domain.OverallScores;
import com.ruoyi.project.knowledge.service.DataOptimizationService;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UploadService {
    @Autowired
    private DataAttributeExtractionService dataAttributeExtractionService;

    @Autowired
    private EnterpriseBasicInfoService enterpriseBasicInfoService;
    @Autowired
    private DataFusionMapper dataFusionMapper;
    @Autowired
    private DataOptimizationService dataOptimizationService;

    @Autowired
    private DataDecisionService dataDecisionService;

    /**
     * 上传文件名修改
     *
     * @param originalFilename 原上传文件名称
     * @return 定义上传文件名称：上传时间+UUID+原文件名
     */
    public String generateUniqueFilename(String originalFilename) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = dateFormat.format(new Date());
        String randomUUID = UUID.randomUUID().toString();

        String prefix = timestamp + "_" + randomUUID + "_";

        return prefix + originalFilename;
    }

    /**
     * csv文件数据提取
     *
     * @param file 上传的文件
     * @throws IOException
     */
    public void processCsvFile(MultipartFile file) throws IOException {
        try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
             CSVParser csvParser = CSVFormat.DEFAULT.withFirstRecordAsHeader().withTrim().parse(reader)) {

            List<CSVRecord> records = csvParser.getRecords();
            Map<String, Integer> headerMap = csvParser.getHeaderMap();
            List<Map<String, Object>> batchDataList = new ArrayList<>();

            int batchSize = 200;  // 设置批处理大小为200行
            int count = 0;

            for (CSVRecord record : records) {
                Map<String, Object> dataMap = new HashMap<>();

                for (String header : headerMap.keySet()) {
                    int columnIndex = headerMap.get(header);
                    Object value = record.get(columnIndex);
                    dataMap.put(header.replaceAll("\uFEFF", ""), value);
                }

                batchDataList.add(dataMap);
                count++;

                // 当累计数据达到批处理大小或处理到文件末尾时执行批处理写操作
                if (count % batchSize == 0 || count == records.size()) {
                    // 处理批处理数据
//                    for (Map<String, Object> batchData : batchDataList) {
//                        //dataAttributeExtractionService.extractDataInfos(batchData);
//                        enterpriseBasicInfoService.addEnterpriseBasicInfos(dataAttributeExtractionService.extractEnterpriseBasicInfo(batchData));
//                        enterpriseBasicInfoService.addHumanResourceInfos(dataAttributeExtractionService.extractHumanResourceInfos(batchData));
//                        enterpriseBasicInfoService.addBusinessStatusInfos(dataAttributeExtractionService.extractBusinessStatusInfos(batchData));
//                        enterpriseBasicInfoService.addMaterialManagementInfos(dataAttributeExtractionService.extractMaterialManagementInfos(batchData));
//                        enterpriseBasicInfoService.addProductionCapacityInfos(dataAttributeExtractionService.extractProductionCapacityInfos(batchData));
//                        enterpriseBasicInfoService.addSaleCapabilityInfos(dataAttributeExtractionService.extractSaleCapabilityInfos(batchData));
//                    }
//                    batchDataList.clear();  // 清空列表以用于下一批次

                    List<EnterpriseBasicInfo> enterpriseBasicInfos = new ArrayList<>();
                    List<HumanResourceInfo> humanResourceInfos = new ArrayList<>();
                    List<BusinessStatusInfo> businessStatusInfos = new ArrayList<>();
                    List<MaterialManagementInfo> materialManagementInfos = new ArrayList<>();
                    List<ProductionCapacityInfo> productionCapacityInfos = new ArrayList<>();
                    List<SaleCapabilityInfo> saleCapabilityInfos = new ArrayList<>();
                    for (Map<String, Object> batchData : batchDataList) {
                        enterpriseBasicInfos.add(dataAttributeExtractionService.extractEnterpriseBasicInfo(batchData));
                        humanResourceInfos.add(dataAttributeExtractionService.extractHumanResourceInfos(batchData));
                        businessStatusInfos.add(dataAttributeExtractionService.extractBusinessStatusInfos(batchData));
                        materialManagementInfos.add(dataAttributeExtractionService.extractMaterialManagementInfos(batchData));
                        productionCapacityInfos.add(dataAttributeExtractionService.extractProductionCapacityInfos(batchData));
                        saleCapabilityInfos.add(dataAttributeExtractionService.extractSaleCapabilityInfos(batchData));
                    }
                    enterpriseBasicInfoService.addEnterpriseBasicInfos(enterpriseBasicInfos);
                    enterpriseBasicInfoService.addHumanResourceInfos(humanResourceInfos);
                    enterpriseBasicInfoService.addBusinessStatusInfos(businessStatusInfos);
                    enterpriseBasicInfoService.addMaterialManagementInfos(materialManagementInfos);
                    enterpriseBasicInfoService.addProductionCapacityInfos(productionCapacityInfos);
                    enterpriseBasicInfoService.addSaleCapabilityInfos(saleCapabilityInfos);
                    batchDataList.clear();  // 清空列表以用于下一批次
                }

            }
        }
    }
    public void insertBusiness(){
        List<BusinessStatusScores> list = new BusinessStatusAlgorithm().compute(dataFusionMapper.getBusinessStatusAggInfos("", ""));

        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<BusinessStatusScores> batchList = list.subList(i, end);
            dataFusionMapper.insertBusiness(batchList);
        }
    }

    public void insertHuman() {
        List<HumanResourceScores> list = new HumanResourceAlgorithm().compute(dataFusionMapper.getHumanResourceAggInfos("", ""));
        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<HumanResourceScores> batchList = list.subList(i, end);
            dataFusionMapper.insertHuman(batchList);

        }

    }

    public void insertMaterialManagementScores() {
        List<MaterialManagementScores> list = new MaterialManagementAlgorithm().compute(dataFusionMapper.getMaterialManagementAggInfos("", ""));
        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<MaterialManagementScores> batchList = list.subList(i, end);
            dataFusionMapper.insertMaterial(batchList);

        }
    }

    public void insertQualityScores() {
        List<QualityScores> list = new QualityAlgorithm().compute(dataFusionMapper.getQualityAggInfos("", ""));
        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<QualityScores> batchList = list.subList(i, end);
            dataFusionMapper.insertQuality(batchList);
        }
    }

    public void insertPriceScore() {
        List<PriceScores> list = new PriceAlgorithm().compute(dataFusionMapper.getPriceAggInfos("", ""));
        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<PriceScores> batchList = list.subList(i, end);
            dataFusionMapper.insertPrice(batchList);

        }
    }

    public void insertServiceScore() {
        List<ServiceScores> list = new ServiceAlgorithm().compute(dataFusionMapper.getServiceAggInfos("", ""));
        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<ServiceScores> batchList = list.subList(i, end);
            dataFusionMapper.insertService(batchList);

        }
    }

    public void insertTechScore() {
        List<TechnologyScores> list = new TechnologyAlgorithm().compute(dataFusionMapper.getTechnologyAggInfo("", ""));
        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<TechnologyScores> batchList = list.subList(i, end);
            dataFusionMapper.insertTechnologyScore(batchList);
        }
    }

    public void insertScore() {
        Thread thread = new Thread(() -> {
            insertBusiness();
            insertHuman();
            insertMaterialManagementScores();
            insertQualityScores();
            insertPriceScore();
            insertServiceScore();
            insertTechScore();
            dataOptimizationService.insertOverallScores("","",0);
            insertCcfScores();
        });
        thread.start();
    }
    public void insertCcfScores(){
        List<OverallScores> overallScores = dataOptimizationService.getOverallScores("", "", 0);
        List<OverallScores> latestYearOverallScores = dataDecisionService.filterLatestYearData(overallScores);
        List<CcfScores> list = new CcfAlgorithm().compute(latestYearOverallScores, 0.75f, 0.25f);
        // 分批插入
        int batchSize = 1000; // 每批插入的数量，可根据数据库性能调整
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            List<CcfScores> batchList = list.subList(i, end);
            dataFusionMapper.insertCcfScore(batchList);
        }
    }

}